package com.taotao.ToDoList;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;

import java.util.ArrayList;

public class ActivityMain extends FragmentActivity
        implements FragmentInput.OnInputToDoItemListener, LoaderManager.LoaderCallbacks<Cursor> {
    private ArrayList<ToDoItem> todoItems;
    private ToDoItemAdapter adapter;

    private FragmentList fragmentList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragmentList = (FragmentList) getSupportFragmentManager().findFragmentById(R.id.fragment_list);
        todoItems = new ArrayList<ToDoItem>();
        adapter = new ToDoItemAdapter(this, R.layout.listitem_todo, todoItems);
        fragmentList.setListAdapter(adapter);

        getSupportLoaderManager().initLoader(0, null, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getSupportLoaderManager().restartLoader(0, null, this);
    }

    @Override
    public void onInputToDoItem(String item) {
        ContentResolver cr = getContentResolver();
        ContentValues values = new ContentValues();
        values.put(ToDoContentProvider.KEY_TASK, item);
        values.put(ToDoContentProvider.KEY_CREATION_DATE, System.currentTimeMillis());
        cr.insert(ToDoContentProvider.CONTENT_URI, values);
        getSupportLoaderManager().restartLoader(0, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, ToDoContentProvider.CONTENT_URI, null, null, null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        int keyTaskIndex = cursor.getColumnIndexOrThrow(ToDoContentProvider.KEY_TASK);
        todoItems.clear();
        while (cursor.moveToNext()) {
            ToDoItem newItem = new ToDoItem(cursor.getString(keyTaskIndex));
            todoItems.add(newItem);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }
}
